

import datetime


# 命令行进度
class Progress(object):
    def __init__(self, total_size) -> None:
        self.total_size = total_size
        self.progress_x = 0
        self.progress_length = 40
        self.start_flag = False
        self.title = None
        self.start_time = None

    def start(self, title):
        self.start_flag = True
        self.title = title
        self.start_time = datetime.datetime.now()
        print("\r" + title + ": [" + "-"*self.progress_length + "]", end='')

    def update(self, x):
        if not self.start_flag:
            self.start('status')
        x = int(x * self.progress_length // 100)
        print("\r" + self.title + ": [" + "#" * x + "-" * (self.progress_length - x) + "]", end='')
        self.progress_x = x

    def end(self):
        if not self.start_flag:
            self.start('status')
        print("\r" + self.title + ": [" + "#"*self.progress_length + "]")
        elapsed = (datetime.datetime.now() - self.start_time)
        speed = (self.total_size / (1024 * 1024) / elapsed.total_seconds())
        print("下载完成! 耗时: {0}, 下载速度: {1:.2f} MB/s, 文件大小: {2}".format(
            str(elapsed), speed, format_size(self.total_size)
        ))
